package J.算法.买卖股票问题;

public class _121买卖股票的最佳时机 {

    /**
     * 字节码 维护一个最小数值 和当前最佳结果
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {

        int minPrice = Integer.MAX_VALUE;
        int maxres = Integer.MIN_VALUE;

        for (int price:prices){
            if (price < minPrice){
                minPrice = price;
            }else {
                maxres = maxres > (price-minPrice )? maxres: (price-minPrice);
            }

        }
        return maxres == Integer.MIN_VALUE?0:maxres;

    }

    /**
     * 动态规划
     * @param prices
     * @return
     */
    public int maxProfit1(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
            dp[i][1] = Math.max(dp[i-1][1],-prices[i]);
        }

        return dp[prices.length-1][0];
    }

    /**
     * 状态压缩
     * @param prices
     * @return
     */
    public int maxProfit2(int[] prices) {
//        int[][] dp = new int[prices.length][2];
//        dp[0][0] = 0;
//        dp[0][1] = -prices[0];
//        for (int i = 1; i < prices.length; i++) {
//            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
//            dp[i][1] = Math.max(dp[i-1][1],-prices[i]);
//        }
//
//        return dp[prices.length-1][0];

        int dp_0 = 0;
        int dp_1 =  -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp_0 = Math.max(dp_0,dp_1+prices[i]);
            dp_1 = Math.max(dp_1,-prices[i]);

        }
        return dp_0;
    }
}
